<template>
  <div class="calculator">
    <div class="display">{{current || '0'}}</div>
    <div class="btn" @click="clear">AC</div>
    <div class="btn">+/-</div>
    <div class="btn">%</div>
    <div class="btn" @click="divide">÷</div>
    <div class="btn" @click="append('7')">7</div>
    <div class="btn" @click="append('8')">8</div>
    <div class="btn" @click="append('9')">9</div>
    <div class="btn" @click="ride">x</div>
    <div class="btn" @click="append('4')">4</div>
    <div class="btn" @click="append('5')">5</div>
    <div class="btn" @click="append('6')">6</div>
    <div class="btn" @click="subed">-</div>
    <div class="btn" @click="append('1')">1</div>
    <div class="btn" @click="append('2')">2</div>
    <div class="btn" @click="append('3')">3</div>
    <div class="btn" @click="added">+</div>
    <div class="btn zero" @click="append('0')">0</div>
    <div class="btn" @click="dot">.</div>
    <div class="btn" @click="equal">=</div>
  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    },
    data() {
      return {
        previous:null,// 第一个数字
        current: '',
        operator: null,//第二个数字
        operatorClicked :false,//定义一个布尔值，
      }
    },
    methods: {
      clear() {
        this.current = '';
      },
      append(number) {
        //if函数是用来判断operatorClicked为真，使输出为空
        if (this.operatorClicked){
          this.current = '';
          this.operatorClicked = false;
        }
        this.current =`${this.current}${number}`;
      },
      dot() {
        if (this.current.indexOf('.') === -1) {
          this.append('.');
        }
      },
      setPrevious(){
        this.previous = this.current;//保存第一个输入的值
        this.operatorClicked = true;
      },
      //除法：divide
      divide() {
        this.operator = (a, b) =>b / a;
        this.setPrevious();
      },
      ride() {
        this.operator = (a, b) => a * b;
        this.setPrevious();
      },
      subed() {
        this.operator = (a, b) => b - a;
        this.setPrevious();
      },
      added() {
        this.operator = (a, b) => a + b;
        this.setPrevious();
      },
      equal(){
        this.current = `${this.operator(
            parseFloat(this.current),
            parseFloat(this.previous)
        )}`;
        this.previous = null;
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .calculator {
    margin: 0 auto; /*居中*/
    width: 400px; /*宽是400像素*/
    font-size: 40px; /*字体大小为40像素*/
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-auto-rows: minmax(50px, auto);
  }

  .display {
    grid-column: 1/5;
    background-color: black;
    color: white;
  }

  .zero {
    grid-column: 1 / 3;
  }

  .btn {
    background-color: #eee;
    border: 1px solid #333;
  }
</style>
